

package com.yungu.swift.api.route.v1.passenger;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.api.base.BaseApi;
import com.yungu.swift.api.utils.RandomUtil;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.model.dto.PassengerLogDto;
import com.yungu.swift.assets.passenger.model.vo.PassengerVo;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.model.dto.CommonIdentifyDto;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.system.marketing.model.dto.MarketingGiftCodeDto;
import com.yungu.swift.system.marketing.model.dto.MarketingGiftDto;
import com.yungu.swift.system.marketing.service.MarketingGiftCodeService;
import com.yungu.swift.system.marketing.service.MarketingGiftService;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.ValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

import static com.yungu.swift.assets.passenger.model.enums.PassengerErrorEnum.*;

/**
 * @author Zerrion
 * @version 1.0
 * @description
 * @date 2018/9/23 17:54
 */
@Controller
@RequestMapping("/api/v1/passenger")
@Api(value = "【乘客】【优惠券】乘客优惠券接口", tags = "乘客优惠券相关操作")
public class PassengerCouponApi extends BaseApi {

    @Reference
    private MarketingGiftService marketingGiftService;
    @Reference
    private PassengerService passengerService;
    @Reference
    private CommonSmsService commonSmsService;
    @Reference
    private MarketingGiftCodeService marketingGiftCodeService;


    @RequestMapping(value = "/drawQrCodeGift", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "领取二维码礼包接口", notes = "")
    public ResponseData drawQrCodeGift(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,
            @ApiParam(name = "mobile", value = "手机号", required = true) @RequestParam String mobile,
            @ApiParam(name = "identifyCode", value = "验证码", required = true) @RequestParam String identifyCode,
            @ApiParam(name = "giftUuid", value = "礼包uuid", required = true) @RequestParam String giftUuid,
            @ApiParam(name = "cid", value = "渠道ID", required = false) @RequestParam(required = false) String cid) {
        String decryptMobile = RandomUtil.randomDecrypt(mobile);
        //判断电话是否准确
        if (!ValidateUtils.validateMobile(decryptMobile)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "请输入正确的手机号");
        }
        String decryptIdentifyCode = RandomUtil.randomDecrypt(identifyCode);
        if (decryptIdentifyCode.length() != MagicConstant.INT_FOUR) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "请输入正确的验证码");
        }

        //校验验证码是否存在
        ResponseData identifyData = ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "验证失败");
        String mobileTop3 = decryptMobile.substring(0, 3);
        CommonIdentifyDto identify = null;
        if (!mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO)) {
            Map<String, Object> paramMap = MapUtils.build(8);
            paramMap.put("mobile", decryptMobile);
            paramMap.put("identifyCode", decryptIdentifyCode);
            paramMap.put("status", CommonConstant.IDENTIFY_CODE_STATUS_UNUSED);
            paramMap.put("appid", appid);
            identify = commonSmsService.get(paramMap).getData();
        }

        if (mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO) || identify != null) {
            //查找是否存在用户
            Map<String, Object> map = MapUtils.build(4);
            map.put("mobile", decryptMobile);
            map.put("appid", appid);
            PassengerDto passengerDto = passengerService.get(map).getData();
            // 判断当前礼包状态
            MarketingGiftDto currentMarketingGift = marketingGiftService.get(MapUtils.build("uuid", giftUuid)).getData();
            ResponseData validateData = validateGift(currentMarketingGift, passengerDto);
            if (!validateData.isSuccess()) {
                return validateData;
            }
            //乘客相关信息
            PassengerLogDto passengerLog = new PassengerLogDto();
            //乘客新增
            PassengerDto passenger = new PassengerDto();
            passenger.setMobile(decryptMobile);
            passenger.setAppid(appid);

            //该方法如果不存在则会进行注册 如果存在则直接获取对应的信息
            ResponseData<PassengerVo> login = passengerService.login(passenger, passengerLog, 0, giftUuid);
            if (login.isSuccess()) {
                //用户的验证码设置为已使用
                if (!mobileTop3.equals(MagicConstant.STRING_ONE_FOUR_TWO)) {
                    //更新验证码
                    identify.setStatus(CommonConstant.IDENTIFY_CODE_STATUS_USED);
                    commonSmsService.edit(identify);
                }
                PassengerVo passengerVo = login.getData();
                // 领取二维码礼包
                return marketingGiftService.drawQrCodeGift(appid, passengerVo.getUuid(), giftUuid, cid, passengerDto == null);
            } else {
                return login;
            }
        } else {
            return identifyData;
        }
    }


    @RequestMapping(value = {"/token/drawCdkeyGift"}, method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    @ApiOperation(value = "兑换/口令码领取礼包接口", notes = "")
    public ResponseData drawCdkeyGift(
            @ApiParam(name = "appid", value = "APP标识", required = true) @RequestParam String appid,


            @ApiParam(name = "code", value = "兑换/口令码", required = true) @RequestParam String code,
            HttpServletRequest request) {

        //输入检查
        String giftCode = "[A-Za-z0-9\u4e00-\u9fa5]{1,20}";
        if (!Pattern.matches(giftCode, code)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "非法输入");
        }
        //验证兑换码有效性
        ResponseData<Boolean> result = marketingGiftCodeService.verifyCode(code);
        if (result.isSuccess() && Objects.equals(Boolean.TRUE, result.getData())) {
            MarketingGiftCodeDto marketingGiftCodeDto = marketingGiftCodeService.get(MapUtils.build("code", code)).getData();
            String userUuid = getUserUid(request), giftUuid = marketingGiftCodeDto.getGiftUuid();
            //查找是否存在用户
            PassengerDto passengerDto = passengerService.get(userUuid).getData();
            // 判断当前礼包状态
            MarketingGiftDto currentMarketingGift = marketingGiftService.get(giftUuid).getData();
            ResponseData validateData = validateGift(currentMarketingGift, passengerDto);
            if (!validateData.isSuccess()) {
                return validateData;
            }
            //领取发放
            ResponseData<Map<String, Object>> giftData = marketingGiftService.drawQrCodeGift(appid, userUuid, giftUuid, null, false);
            if (giftData.isSuccess() && giftData.getData() != null) {
                // 只有兑换码类型为1的才需要设置为失效
                if (marketingGiftCodeDto.getCodeType() == 1) {
                    ResponseData responseData = marketingGiftCodeService.disableCode(code);
                    if (!responseData.isSuccess()) {
                        return ResponseData.buildErrorResponse(responseData.getErrCode(), responseData.getMsg());
                    }
                }
            }
            return giftData;
        }
        return result;

    }

    private ResponseData<Void> validateGift(MarketingGiftDto currentMarketingGift, PassengerDto passengerDto) {
        if (currentMarketingGift == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "活动未开始或活动已失效");
        }
        if (currentMarketingGift.getLimitDrawType() != null) {
            // 礼包为限制新用户礼包且当前用户不是新用户
            if (currentMarketingGift.getLimitDrawType() == CommonConstant.LIMIT_DRAW_TYPE_NEW_USER && passengerDto != null) {
                return ResponseData.buildErrorResponse(NEW_USER_ACTIVITY.getCode(), NEW_USER_ACTIVITY.getMsg());
                // 礼包为限制老用户礼包且当前用户不是老用户
            } else if (currentMarketingGift.getLimitDrawType() == CommonConstant.LIMIT_DRAW_TYPE_OLD_USER && passengerDto == null) {
                return ResponseData.buildErrorResponse(OLD_USER_ACTIVITY.getCode(), OLD_USER_ACTIVITY.getMsg());
            }
        }
        // 判断活动是否开启 或者 当前时间小于活动开始时间
        if (System.currentTimeMillis() < currentMarketingGift.getEffectiveDate().getTime()) {
            return ResponseData.buildErrorResponse(ACTIVITY_NOT_OPEN.getCode(), ACTIVITY_NOT_OPEN.getMsg());

        }
        // 当前时间大于活动结束时间
        if (currentMarketingGift.getStatus() == CommonConstant.STATUS_CLOSED || currentMarketingGift.getExpiryDate().getTime() < System.currentTimeMillis()) {
            return ResponseData.buildErrorResponse(ACTIVITY_CLOSED.getCode(), "活动已结束");
        }
        // 领取数量
        if (currentMarketingGift.getRemainNumber() <= 0) {
            return ResponseData.buildErrorResponse(GIFT_QUANTITY_LACK.getCode(), GIFT_QUANTITY_LACK.getMsg());
        }
        return ResponseData.buildSuccessResponse(null);
    }
}
